import Mock from 'mockjs';
import { API_CODE } from '@/api/constant';

// 登录
Mock.mock(/\/api\/user\/login/, 'post', (options: any) => {
  const { username, password } = JSON.parse(options.body);

  if (username === 'admin' && password === '123456') {
    return {
      code: API_CODE.SUCCESS,
      message: '登录成功',
      data: {
        token: 'mock-token-' + Mock.Random.guid(),
        userInfo: {
          id: '1',
          username: 'admin',
          name: 'Admin User',
          avatar: '',
          roles: ['admin']
        }
      }
    };
  } else {
    return {
      code: API_CODE.UNAUTHORIZED,
      message: '用户名或密码错误',
      data: null
    };
  }
});

// 登出
Mock.mock(/\/api\/user\/logout/, 'post', () => {
  return {
    code: API_CODE.SUCCESS,
    message: '登出成功',
    data: null
  };
});

// 获取用户信息
Mock.mock(/\/api\/user\/info/, 'get', () => {
  return {
    code: API_CODE.SUCCESS,
    message: '获取用户信息成功',
    data: {
      id: '1',
      username: 'admin',
      name: 'Admin User',
      avatar: '',
      roles: ['admin']
    }
  };
});

// 获取用户列表
Mock.mock(/\/api\/user\/list/, 'get', (options: any) => {
  const { page = 1, pageSize = 10 } = options.url.match(/page=(\d+)&pageSize=(\d+)/)
    ? {
        page: parseInt(options.url.match(/page=(\d+)/)[1]),
        pageSize: parseInt(options.url.match(/pageSize=(\d+)/)[1])
      }
    : { page: 1, pageSize: 10 };

  const list = [];
  for (let i = 0; i < pageSize; i++) {
    list.push(
      Mock.mock({
        id: '@guid',
        username: '@word(5, 10)',
        name: '@cname',
        'roles|1': [['admin'], ['user'], ['guest']],
        email: '@email',
        phone: /^1[3-9]\d{9}$/,
        'status|1': ['active', 'inactive'],
        createTime: '@datetime'
      })
    );
  }

  return {
    code: API_CODE.SUCCESS,
    message: '获取用户列表成功',
    data: {
      list,
      total: 100,
      page,
      pageSize
    }
  };
});

// 获取用户详情
Mock.mock(/\/api\/user\/detail\/\w+/, 'get', (options: any) => {
  const id = options.url.match(/\/api\/user\/detail\/(\w+)/)[1];

  return {
    code: API_CODE.SUCCESS,
    message: '获取用户详情成功',
    data: Mock.mock({
      id,
      username: '@word(5, 10)',
      name: '@cname',
      'roles|1': [['admin'], ['user'], ['guest']],
      email: '@email',
      phone: /^1[3-9]\d{9}$/,
      'status|1': ['active', 'inactive'],
      createTime: '@datetime',
      lastLoginTime: '@datetime'
    })
  };
});
